﻿/**
 * 图片自动上传功能
 * 
 */
(function( E ){

var pluginName = 'autoUploadImg',
	Event = E.mod('Event'),
	Message = jQEditor.mod('Message'),
	wait_time = 30000,//上传图片提示信息显示时间
	start_tips = '检测到有外链图片[num]张，正在自动上传第[n]张，暂时请不要源码编辑',
	end_tips = '自动上传完成',
	stop_tips = '图片自动处理已停止！！',
	//标志是否是初始化时候,初始状态会对name=uploaded的img上传
	oncomplete = true;
//给编辑器创建完成绑定自动上传方法
Event.bind("oncomplete", function(){
	setTimeout(function(){
		if(!AutoUploadImg.uploading){
			AutoUploadImg.start();
			//给编辑器内容变化事件绑定自动上传方法
			Event.bind("onmonitor", function(){
				if(!AutoUploadImg.uploading){
					//修改标志为非初始状态
					oncomplete = false;
					AutoUploadImg.start();
				}
			});
		}
	}, 10000);
});
//这使用plugin的方式完全是为了方便外部配置相关信息
E.plugin(pluginName, {
	settings : {
		//判断图片是否是来自其他域上的【返回false表示不需要自动上传，返回true表示需要自动上传】
		checkImg : function(img){
			var reg = /^(http\:\/\/)[\w.\/-]+\.(jpg|jpeg|gif|png)/i ,
				src = $.trim(img.attr('src'));
			//非法地址或者非其他域名下的地址都不需要处理
			if(!src || src.length< 12 
				|| /(hudong|baike).com/i.test( src )
				|| !reg.test(src)){//src.length< 12   ====  'http://x.jpg'
				return false;
			}
			return true;
		},
		/*自动上传图片地址
		 *[非小百科下使用必须在外部重写该方法]
		 *[返回数据格式如{action:'www.abc.com', postParms:{name:'img'}}，
		 *如果没有需要post提交的参数则可以直接返回string类型的url]
		 */
		getUrlAction : function(){//这里默认在小百科下面
			var url = "http://a5.att.baike.com/",
				doctitle = $('#art_title').length ? $('#art_title').val() : '',
				iden = $('#curuser_iden').length ? $('#curuser_iden').val() : '',
				art_iden=$('#art_iden').length ? $('#art_iden').val() : '',
				type = $('#type').val() == 19? 19: 14;//[14]主站文章=14，小百科19
			url +='uploadUrl.wiki?curuser_iden='+iden+'&doc_title='+encodeURI(doctitle);
			url += '&type=' + type;
			url += '&host=' + encodeURIComponent('http://' + location.hostname + '/index.php?m=attachment&a=upload_article_img&upload_auto=1');
			return url;
		},
		//图片最大可显示宽度
		max_width : 600
	},
	//图片上传相关参数
	upload_parms : {
		img_src_action : 'baike_article_create.php',
		picAlign : 'center',
		picAlt : '',
		picWidthHeight : 1
	},
	//图片上传完成回调方法替换原始图片
	update : function( img_src, img_link ){
		var self = this,
			uploadObj = AutoUploadImg,
			uploading_img = uploadObj.uploading_img,
			img = new Image(),
			align = 'left',//默认居左显示
			imgfig = '_950',//默认显示950图片
			new_src = img_src.replace(/_140|_s|_950/i, imgfig);
		//如果已经中断上传则返回
		if(!uploadObj.uploading){
			return ;
		}
		//上传失败
		if(img_src == 'error'){
			//标志该图片已经传过
			uploading_img.attr('name','uploaded');
			//继续下一张图片上传
			return uploadObj.upload();
		}
		img.onload = function() {
			var width=parseInt(img.width), imgw=0,title = '';
			if($('#art_title').length){
				title = $('#art_title').val();
			}else if($('#_doc_title').length){
				title = $('#_doc_title').val();
			}else if($('#title').length){
				title = $('#title').val();
			}
			if(width > self.settings.max_width ) {
				imgw = self.settings.max_width;
			}else {
				imgw = width;
			}
			html = self.getImgHtml({new_src : new_src,
									img_link : img_link,
									imgw : imgw,
									width : width,
									align : align,
									title : title});
			//替换原始图片
			uploading_img.replaceWith(html);
			//开始下一张图片上传
			uploadObj.upload();
			img.onload = function(){};
		};
		img.onerror = function() {
			uploadObj.upload();
		}
		img.src = new_src;
	},
	//中断上传
	stop_upload : function(){
		AutoUploadImg.uploading = false;
		//处理完毕提示
		Message.showNotice(stop_tips, 3000);
		//防止图片替换操作，编辑器区域大小不变
			E.monitor(pluginName);
	},
	/*
	 *获取上传后图片html
	 *@parms : 参数列表分别是：
	 *@new_src : 新图片地址
	 *@img_link : 新图片浏览地址
	 *@imgw : 新图片可显示宽度
	 *@align : 新图片对齐方式
	 *@title : 新图片提示信息和摘要内容
	 *@width : 新图片原始大小
	*/
	getImgHtml : function(parms){
		var self = this,
			html = '<IMG title="' + parms.title + '" alt="' + parms.title + '"';
		//图片大小超过最大值max_width则给img标签加width属性
		if(parms.width > self.settings.max_width) {
			html += ' width="' + parms.imgw + '"';
		}
		html += ' src="' + parms.new_src + '"/>';
		return html;
	}
});
//自动上传对象

var AutoUploadImg = {
	//是否正在上传图片
	uploading : false,
	//上传图片表单id
	formId : 'auto_upload_img_form',
	//上传图片iframe  id
	iframefig : 'auto_upload_img_iframe',
	//正在上传的图片
	uploading_img : null,
	//缓存需要上传的图片
	upload_imgs : [],
	//上传图片列表大小
	upload_size : 0,
	//启动方法
	start : function(){
		var self = this,
			plugin = E.plugin(pluginName),
			settings = plugin.settings,
			checkImg = settings.checkImg,
			imgs = E.$('img'),
			upload_imgs = self.upload_imgs = [];//这里对upload_imgs重新复制，清空内容
		if(imgs.length == 0 || self.uploading){
			return ;
		}
		imgs.each(function(i,item){
			if(checkImg($(this))){
				//第一次加载时候不对name = uploaded的img过滤
				if($(this).attr('name') != 'uploaded'){
					upload_imgs.push($(this));
				}else if(oncomplete){//如果在编辑器初始化时候，不需要过滤name属性等于uploaded的img
					upload_imgs.push($(this));
				}
			}
		});
		if(upload_imgs.length<1){
			return ;
		}
		//初始化上传表单和iframe
		self.init(settings, plugin.upload_parms);
		//开始上传
		self.uploading = true;
		//记录图片列表大小
		self.upload_size = upload_imgs.length;
		//显示提示信息
		Message.showNotice(start_tips.replace('[num]',self.upload_size).replace('[n]',1), wait_time);
		self.upload();
	},
	//初始化上传表单和iframe,该函数只需执行一次
	init : function(settings, upload_parms){
		var self = this,
			iframe = null,
			form = null,
			formId = self.formId,
			iframefig = self.iframefig,
			action = settings.getUrlAction();
		//增加iframe
		$('body').append('<iframe id="'+iframefig+'" name="'+iframefig+'" width="0" height="0"></iframe>');
		//增加form表单
		$('body').append('<form action="" target="'+iframefig+'" method="POST" id="'+formId+'" onsubmit="return true;" enctype="application/x-www-form-urlencoded"></form>');
		form = $('form#'+formId);
		iframe = $('iframe#'+iframefig);
		//设置表单action和相关参数
		if(typeof action === 'string'){
			form.attr('action',action);
		}else if(typeof action === 'object'){
			form.attr('action', action.action);
			if(typeof action.postParms === 'object') {
				var parms = action.postParms;
				for(var k in parms) {
					form.append('<input type="hidden" name="'+k+'" value="'+parms[k]+'">');
				}
			}
		}
		//增加上传图片地址
		form.append('<input type="hidden" name="img_url">');
		for(var k in upload_parms){
			form.append('<input type="hidden" name="'+k+'" value="'+upload_parms[k]+'">');
		}
		//重写初始化函数，避免重复初始化
		self.init = function(){};
	},
	/*
		上传图片 
	*/
	upload : function(){
		var self = this,
			upload_imgs = self.upload_imgs,
			formId = self.formId,
			iframefig = self.iframefig,
			form = $('form#'+formId),
			iframe = $('iframe#'+iframefig);
		if(upload_imgs.length){
			//存储当前正在上传图片
			self.uploading_img = upload_imgs.pop();
			form.find('input[name=img_url]').val(self.uploading_img.attr('src'));
			//显示提示信息
			Message.showNotice(start_tips.replace('[num]',self.upload_size).replace('[n]',self.upload_size - upload_imgs.length), wait_time);
			form[0].submit();
		}else{
			self.uploading = false;
			//处理完毕提示
			Message.showNotice(end_tips,3000);
			//防止图片替换操作，编辑器区域大小不变
			E.monitor(pluginName);
		}
	}
}


})(jQEditor);